package com.iptv.grape.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;

import java.lang.ref.WeakReference;
import java.util.List;

import static android.content.Context.ACTIVITY_SERVICE;
@SuppressLint("NewApi")
public class ActMgr {

    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public  boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 返回当前的应用是否处于前台显示状态
     * @param packageName
     * @return
     */
    private  boolean isForeground(Activity context, String packageName) {
        //_context是一个保存的上下文
        ActivityManager __am = (ActivityManager) context.getApplicationContext().getSystemService(ACTIVITY_SERVICE);

        List<ActivityManager.RunningTaskInfo> taskInfo = __am.getRunningTasks(1);
       ComponentName componentInfo = taskInfo.get(0).topActivity;
        String nowClassName = componentInfo.getClassName();
        componentInfo.getPackageName();
        if (nowClassName.contains(packageName)) {
            return true;
        } else {
            return false;
        }

    }

    private WeakReference<Activity> sCurrentActivityWeakRef;

    private ActMgr() {

    }

    public static ActMgr istc() {
        return Instc.ISTC;
    }
    private interface  Instc{
        ActMgr ISTC = new ActMgr();
    }

    public Activity getCurrentActivity() {
        Activity currentActivity = null;
        if (sCurrentActivityWeakRef != null) {
            currentActivity = sCurrentActivityWeakRef.get();
        }
        return currentActivity;
    }

    public void setCurrentActivity(Activity activity) {
        sCurrentActivityWeakRef = new WeakReference<>(activity);
    }



}
